package Demo71;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Stack;

/**
 *  基本计算器II
 * https://leetcode.cn/problems/basic-calculator-ii/submissions/561996672/
 */

class Solution {
    public int calculate(String s) {
        // 栈
        Deque<Integer> stack = new ArrayDeque<>();

        char[] chars = s.toCharArray();
        int i = 0, len = chars.length;
        char op = '+';
        while(i < len) {
            if(chars[i] == ' ') {
                i++;
            }else if (chars[i] >= '0' && chars[i] <= '9'){
                int tmp = 0;
                while(i < len && chars[i] >= '0' && chars[i] <= '9') {
                    tmp *= 10;
                    tmp += chars[i++] - '0';
                }
                if(op == '+') {
                    stack.push(tmp);
                }else if(op == '-'){
                    stack.push(-tmp);
                }else if(op == '*') {
                    stack.push(stack.pop() * tmp);
                }else {
                    stack.push(stack.pop() / tmp);
                }

            }else {
                op = chars[i++];
            }
        }
        int ret = 0;
        while(!stack.isEmpty()) {
            ret += stack.pop();
        }
        return ret;
    }
}
class Demo {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int calculate = solution.calculate(" 3+5 / 2 ");
        System.out.println(calculate);
    }
}